package com.example.huangliting.experimentalarrangementsystem.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.example.huangliting.experimentalarrangementsystem.R;
import com.example.huangliting.experimentalarrangementsystem.bean.ClassInfo;
import com.example.huangliting.experimentalarrangementsystem.util.DateUitls;
import com.example.huangliting.experimentalarrangementsystem.util.DialogButtonListener;
import com.example.huangliting.experimentalarrangementsystem.util.DialogUtil;
import com.example.huangliting.experimentalarrangementsystem.util.HttpUtils;
import com.example.huangliting.experimentalarrangementsystem.util.Utils;
import com.example.huangliting.experimentalarrangementsystem.widget.ItemGroup;

import org.json.JSONObject;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class MyScheduleDetailAct extends AppCompatActivity {

    private final String getClassDetailUrl = HttpUtils.headerUrl+"timetable/getClassDetail";
    private final String deleteClassUrl = HttpUtils.headerUrl+"timetable/deleteClass";
    private ItemGroup classNameIG, aNameIG, showAddressIG, classTimeIG,teacherIG,classifyIg,classLenIG,batchNumIG,lstatusIG;
    private Context mContext;
    private Button backBtn;
    private Button cancelBtn;
    private int cid;
    private JSONObject dataJSON = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_schedule_detail);
        mContext = this;
        Intent intent = getIntent();
        cid = intent.getIntExtra("cid",0);
        int dbDivision = intent.getIntExtra("dbDivision",0);
        //1是课程
        if(dbDivision == 1){
            Map<String, String> params = new HashMap<String, String>();
            params.put("cid", String.valueOf(cid));
            getDataByCid(params, "utf-8");
        }

        initView();
    }

    private void initView() {
        classNameIG = (ItemGroup) findViewById(R.id.className_ig_detail);
        aNameIG = (ItemGroup) findViewById(R.id.aName_ig_detail);
        showAddressIG = (ItemGroup) findViewById(R.id.address_ig_detail);
        classTimeIG = (ItemGroup) findViewById(R.id.classTime_ig_detail);
        teacherIG = (ItemGroup) findViewById(R.id.teacher_ig_detail);
        classLenIG = (ItemGroup) findViewById(R.id.classLen_ig_detail);
        classifyIg = (ItemGroup) findViewById(R.id.classify_ig_detail);
        batchNumIG = (ItemGroup) findViewById(R.id.batchNum_ig_detail);
        lstatusIG = (ItemGroup) findViewById(R.id.lstatus_ig_detail);
        cancelBtn = findViewById(R.id.submit_btn_cancel);
        cancelBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                DialogUtil dialogUtil = new DialogUtil();
                dialogUtil.show(mContext, "确认取消课程吗?", new DialogButtonListener() {
                    @Override
                    public void sure() {
                        //Toast.makeText(mContext, "确认修改", Toast.LENGTH_SHORT).show();
                        Map<String, String> params = new HashMap<String, String>();
                        params.put("cid", String.valueOf(cid));
                        deleteDataByCid(params, "utf-8");
                    }

                    @Override
                    public void cancel() {
                        //Toast.makeText(mContext, "取消", Toast.LENGTH_SHORT).show();
                    }
                });

            }
        });
        /*返回操作*/
        backBtn = findViewById(R.id.toolbar_left_btn);
        backBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                finish();
            }
        });
    }

    private final String[] items = {"实验","考试","培训","比赛","其他"};
    //获取当周我的课程Json和解析
    Handler myClassHandler = new Handler() {

        @SuppressLint("WrongConstant")
        public void handleMessage(android.os.Message msg) {
            try {
                JSONObject jsonObj = new JSONObject((String) msg.obj);
                dataJSON = jsonObj.getJSONObject("timetable");
                classNameIG.setText(dataJSON.getString("lessonName"));
                aNameIG.setText(dataJSON.getString("applicationName"));
                showAddressIG.setText(dataJSON.getString("lname"));
                /*日期显示*/
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                String classDateStr = dataJSON.getString("classDate");
                Date classdt = null;
                try {
                    classdt = format.parse(classDateStr);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                Calendar cal = Calendar.getInstance();
                cal.setTime(classdt);
                classTimeIG.setText(classDateStr+" "+ DateUitls.formateDay(cal.get(Calendar.DAY_OF_WEEK)));
                teacherIG.setText(dataJSON.getString("tname"));
                classLenIG.setText(dataJSON.getInt("classNum")+"-"+(dataJSON.getInt("classNum")+dataJSON.getInt("classLength")-1)+"节");
                classifyIg.setText(items[dataJSON.getInt("classClassify")]);
                batchNumIG.setText("第"+dataJSON.getString("batchNum")+"批");
                int lstatus = dataJSON.getInt("lstatus");
                if(lstatus==0){
                    lstatusIG.setText("可以使用");
                }else if(lstatus==1){
                    lstatusIG.setText("不可使用");
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    //当周我的课程请求
    private void getDataByCid(final Map<String, String> params, final String encode) {
        Thread t = new Thread() {
            @Override
            public void run() {
                try {
                    URL url = new URL(getClassDetailUrl);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("POST");
                    conn.setConnectTimeout(5000);
                    conn.setReadTimeout(5000);

                    //拼接出要提交的数据的字符串
                    byte[] data = HttpUtils.getRequestData(params, encode).toString().getBytes();

                    //添加post请求的两行属性
                    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    conn.setRequestProperty("Content-Length", String.valueOf(data.length));

                    //设置打开输出流
                    conn.setDoOutput(true);
                    //拿到输出流
                    OutputStream os = conn.getOutputStream();
                    //使用输出流往服务器提交数据
                    os.write(data);
                    if (conn.getResponseCode() == 200) {
                        InputStream is = conn.getInputStream();
                        String text = Utils.getTextFromStream(is);
                        Message msg = myClassHandler.obtainMessage();
                        msg.obj = text;
                        myClassHandler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        };
        t.start();
    }

    //删除我的课程handle
    Handler deleteHandler = new Handler() {

        @SuppressLint("WrongConstant")
        public void handleMessage(android.os.Message msg) {
            try {
                JSONObject jsonObj = new JSONObject((String) msg.obj);
                int isSuccess = jsonObj.getInt("isSuccess");
                if (isSuccess == 0){
                    Toast.makeText(mContext, "取消成功", Toast.LENGTH_LONG).show();
                    finish();
                }else if(isSuccess == 1)
                    Toast.makeText(mContext, "已经过了可以取消课程的时间，需要提前一个工作日取消课程", Toast.LENGTH_LONG).show();
                else if(isSuccess == 2)
                    Toast.makeText(mContext, "取消出错", Toast.LENGTH_LONG).show();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    //删除我的课程请求
    private void deleteDataByCid(final Map<String, String> params, final String encode) {
        Thread t = new Thread() {
            @Override
            public void run() {
                try {
                    URL url = new URL(deleteClassUrl);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("POST");
                    conn.setConnectTimeout(5000);
                    conn.setReadTimeout(5000);

                    //拼接出要提交的数据的字符串
                    byte[] data = HttpUtils.getRequestData(params, encode).toString().getBytes();

                    //添加post请求的两行属性
                    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    conn.setRequestProperty("Content-Length", String.valueOf(data.length));

                    //设置打开输出流
                    conn.setDoOutput(true);
                    //拿到输出流
                    OutputStream os = conn.getOutputStream();
                    //使用输出流往服务器提交数据
                    os.write(data);
                    if (conn.getResponseCode() == 200) {
                        InputStream is = conn.getInputStream();
                        String text = Utils.getTextFromStream(is);
                        Message msg = deleteHandler.obtainMessage();
                        msg.obj = text;
                        deleteHandler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        };
        t.start();
    }
}
